<template>
    <div class="flex flex-col justify-center items-center mt-10">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm w-3/5" status-icon>
            <el-form-item label="旧密码" prop="oldPwd">
                <el-input v-model="form.oldPwd" password clearable show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd">
                <el-input v-model="form.newPwd" password clearable show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPwd">
                <el-input v-model="form.confirmPwd" password clearable show-password />
            </el-form-item>
        </el-form>
        <el-button class="w-2/5" type="primary" :color="themeStore.themeColor"
            @click="submitForm(formRef)">更新</el-button>
    </div>
</template>


<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import { setPwd } from '@/config/api';

import { themeColorStore } from '@/stores'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const themeStore = themeColorStore();

const form = ref({
    oldPwd: '',
    newPwd: '',
    confirmPwd: ''
})
const formRef = ref(null)

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== form.value.newPwd) {
    callback(new Error("两次输入不一致"))
  } else {
    callback()
  }
}


const rules = ref({
    oldPwd: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min:6, max: 20, message: '请输入正确的位数', trigger: 'blur' },
    ],
    newPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min:6, max: 20, message: '请输入正确的位数', trigger: 'blur' },
    ],
    confirmPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
    ]
})
const submitForm = (formRef) => {
    if (!formRef) return
    formRef.validate((valid) => {
        if (valid) {
            setPwd(form.value).then(res => {
                if(res.code == 200){
                    ElMessage.success(res.msg)
                }
                else{
                    ElMessage.error(res.msg)
                }
            })
        } else {
            ElMessage.error('表单校验未通过')
        }
    })
}
</script>


<style scoped>

</style>